package top.mccat.filesystem.resolver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import top.mccat.filesystem.anno.CurrentAccount;
import top.mccat.filesystem.bean.Account;

import javax.servlet.http.HttpServletRequest;

/**
 * @author JMY
 * @Description 获取拦截器并进行解析token到方法注解中
 * @Version 1.0.0
 * @Date 2023/2/24 17:18
 * @Created by JMY
 */
@Slf4j
@Component
public class CurrentAccountMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //判断是否支持使用@CurrentUser注解的参数; 如果该参数注解有@CurrentUser且参数类型是account
        return parameter.getParameterAnnotation(CurrentAccount.class) != null && parameter.getParameterType() == Account.class ;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception
    {
        //注入参数值
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        log.info("get attribute currentAccount ----" + request.getAttribute("currentAccount"));
        return request.getAttribute("currentAccount");
    }
}
